//
// Created by twlin on 2024/8/3.
//
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>


bool bThreadRunning = true;

void *read_control(void *arg)
{
    char buf[100];
    int sock_fd = *static_cast<int*>(arg);

    while(bThreadRunning)
    {
        bzero(buf, 100);
        fgets(buf, 100, stdin);

        if(send(sock_fd, buf, strlen(buf), 0) < 0)
        {
            perror("Error sending data");
//            exit(EXIT_FAILURE);
            break;
        }
    }

    return nullptr;
}

int main(int argc, char *argv[])
{
    int sockfd;
    int bytes;
    char buf[100];
    pthread_t threadId;
    struct sockaddr_in servaddr;

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket error");
        return -1;
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_port = htons(8888);

    if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        perror("connect error");
        close(sockfd);
        return -1;
    }

    if (pthread_create(&threadId, nullptr, read_control, &sockfd) != 0) {
        std::cerr << "Failed to create thread" << std::endl;
        std::exit(EXIT_FAILURE);
    }

    while(1)
    {
//        bzero(buf, 100);
//        fgets(buf, 100, stdin);
//
//        send(sockfd, buf, strlen(buf), 0);

        bzero(buf, 100);
        bytes = recv(sockfd, buf, 100, 0);
        if (bytes == -1)
        {
            if(errno != EWOULDBLOCK || errno != EAGAIN)
            {
                printf("Error, read failed\n");
                //close(sockfd);
                //return -1;
                usleep(10000);
                continue;
            }
        }
        else if(bytes == 0)
        {
            printf("Server close connection.\n");
            close(sockfd);
            break;
        }

        printf("Read bytes %d\n", bytes);
        printf("read_buf: %s\n", buf);
    }

    bThreadRunning = false;

    if (pthread_join(threadId, nullptr) != 0) {
        std::cerr << "Failed to join thread" << std::endl;
        std::exit(EXIT_FAILURE);
    }

    close(sockfd);

    return 0;
}